<template>
  <div class="">
    <el-button
      style="background-color:#fd804c;color: #fff; position: absolute;
        top: 10px;
        right: 10px;
        z-index: 10;"
      @click="sure"
      >确定</el-button
    >
    <div class="amap-wrapper">
      <!-- <el-amap-search-box
        class="search-box"
        :search-option="searchOption"
        :on-search-result="onSearchResult"
      ></el-amap-search-box>-->

      <el-amap
        class="amap-box"
        ref="map"
        :zoom="zoom"
        :center="center"
        :events="events"
        :mapStyle="mapStyle"
      >
        <el-amap-polygon
          v-for="(polygon, index) in polygons"
          :key="index"
          :vid="index"
          :title="polygon.measure"
          :ref="`polygon_${index}`"
          :path="polygon.path"
          editable="true"
          strokeStyle="dashed"
          strokeColor="#FF0000"
          strokeWeight="2"
          strokeOpacity="0.8"
          fillOpacity="0.3"
          fillColor="#1791fc"
          :events="polygon.events"
        ></el-amap-polygon>
      </el-amap>
    </div>

    <div style="width: 360px; position: absolute; top: 10px; left: 10px">
      <el-card class="box-card">
        <el-table :data="polygons" border size="mini" style="width: 100%">
          <el-table-column align="center" label="名称">
            <template slot-scope="scope">
              <div>{{ scope.row.name }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="面积">
            <template slot-scope="scope">
              <div>{{ area ? area : scope.row.measure }}平方米</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="100">
            <template slot-scope="scope">
              <el-button
                @click="edit(scope)"
                v-if="scope.row.path.length > 0"
                style="color: #fc9e76;"
                type="text"
                size="small"
                >编辑</el-button
              >
              <el-button
                @click="draw(scope.$index)"
                v-else
                style="color: #fc9e76;"
                type="text"
                size="small"
                >绘制</el-button
              >
              <el-button
                @click="del(scope)"
                style="color: #fc9e76;"
                type="text"
                size="small"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
    <div class="Y-text-align-right Y-avg-1" style="margin-top: 10px">
      <!-- <el-button                   style="background-color:#fd804c;color: #fff;" @click="addArea">添加商圈</el-button> -->
      <!-- <el-button                   style="background-color:#fd804c;color: #fff;" v-if="isEdit" @click="end">结束编辑</el-button>
      <el-button                   style="background-color:#fd804c;color: #fff;" v-if="isDraw" @click="endDraw">结束绘制</el-button>-->
    </div>
  </div>
</template>
<script>
import Bus from "../../api/bus";
export default {
  props: {
    path: {
      type: Array,
      default: function() {
        return [];
      }
    },
    name: {
      type: String,
      default: function() {
        return "";
      }
    }
  },
  data() {
    let _this = this;
    return {
      falg: true,
      polygonsTwo: [],
      center: [121.44167, 31.181728], //地图中心点坐标 上海
      zoom: 14, //初始化地图显示层级
      mapStyle: "amap://styles/8b6be8ec497009e17a708205348b899a", //设置地图样式
      // searchOption: {
      //   city: "上海",
      //   citylimit: true,
      // },
      input: "",
      isEdit: false,
      pIdx: 0,
      zoom: 14,
      area: 0,
      businessAreaCode: "",
      value: "",
      events: {
        init: o => {},
        click: e => {
          let { lng, lat } = e.lnglat;
          if (_this.isDraw) {
            let arr = [e.lnglat.lng, e.lnglat.lat];
            _this.polygons[_this.pIdx].path.push(arr);
          }
        }
      },
      polygons: [
        // {
        //   path: [],
        //   events: {
        //     click(e) {
        //       _this.clickEdit(_this, this);
        //     },
        //   },
        // },
      ],
      polygonEditor: null,
      isDraw: false
    };
  },
  watch: {},
  activated() {
    //console.log(this.$route.query)
    this.businessAreaCode = this.$route.query.id;
    this.cityCode = this.$route.query.cityCode;
    this.cityName = this.$route.query.cityName;

    this.city();
    this.query();
  },
  mounted() {
    var that = this;

    //console.log(this.businessAreaCode);

    let _this = this;
    setTimeout(function() {
      this.polygons = [];
      let path = _this.path;
      if (path.length > 0) {
        for (let i = 0; i < path.length; i++) {
          const element = path[i];

          let arr = [];
          if (element.aroundLocations.length > 0) {
            for (let j = 0; j < element.aroundLocations.length; j++) {
              const item = element.aroundLocations[j];
              arr.push([item.lng, item.lat]);
            }
          }
          element.path = arr;
          element.events = {
            click(e) {
              _this.clickEdit(_this, this);
            }
          };
          delete element.aroundLocations;
        }
        _this.polygons = path;
      }
    }, 500);
  },
  methods: {
    query() {
      this.$http({
        url: "hsssystemadmin/v1/businessManagement/getCenterCoordinates",
        method: "POST",
        data: {
          cityCode: this.cityCode,
          cityName: this.cityName
        }
      }).then(res => {
        let data = JSON.parse(res.data);
        this.center = data.geocodes[0].location.split(",");
      });
    },
    city() {
      this.$http({
        url:
          "hsssystemadmin/v1/businessManagement/getBusinessMessage?businessAreaCode=" +
          this.businessAreaCode,
        method: "get"
      }).then(res => {
        var data = res.data;

        var polygons = [];

        var obj = {
          path: [],
          businessAreaCode: "",
          name: "",
          events: {
            click(e) {
              _this.clickEdit(_this, this);
            }
          }
        };
        obj.name = data.businessAreaName;
        obj.businessAreaCode = data.businessAreaCode;
        obj.measure = data.businessArea;
        // obj.path = data[i].businessCoordinates[0].aroundLocations
        var element = data.businessCoordinates[0];

        for (var j = 0; j < element.aroundLocations.length; j++) {
          const item = element.aroundLocations[j];
          obj.path.push([item.lng, item.lat]);
        }
        polygons.push(obj);

        this.polygons = polygons;
      });
    },
    onSearchResult(pois) {
      let latSum = 0;
      let lngSum = 0;
      //console.log(pois);
      if (pois.length > 0) {
        let center = pois[0];
        this.lng = center.lng;
        this.lat = center.lat;
        this.address = center.name;
        this.center = [center.lng, center.lat];
        this.markers = [[center.lng, center.lat]];
      }
    },
    // 添加多边形区域
    addArea() {
      if (this.input) {
        if (this.falg == false) {
          this.$message.error("您尚未添加新商圈");
          return;
        }
        this.falg = false;
        let _this = this;
        if (this.isDraw) {
          this.endDraw();
        }

        if (this.isEdit) {
          this.end();
        }

        let obj = {
          path: [],
          name: this.input,
          businessAreaCode: "",
          events: {
            click(e) {
              _this.clickEdit(_this, this);
            }
          }
        };

        this.polygons.push(obj);
        this.polygonsTwo.push(obj);

        if (this.polygons.length > 0) {
          this.draw(this.polygons.length - 1);
        }
        this.input = "";
      } else {
        this.$message.error("请先输入商圈名称");
      }
    },

    // 绘制多边形
    draw(idx) {
      if (this.isEdit) {
        this.end();
      }
      this.pIdx = idx;
      this.isDraw = true;
    },
    // 删除多边形区域
    del(idx) {
      //console.log(idx.row);
      this.$confirm("是否删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$http({
            url:
              "hsssystemadmin/v1/businessManagement/updateBusinessStatus?businessAreaCode=" +
              idx.row.businessAreaCode,
            method: "get"
          }).then(res => {
            this.polygons.splice(idx.$index, 1);
            this.$message.success("删除成功");
          });
        })
        .catch(() => {
          _this.$message.error("已取消");
        });
    },

    clickEdit(vm, polygon) {
      if (vm.isDraw) {
        vm.endDraw();
      }
      if (vm.polygonEditor) {
        vm.end();
      }
      vm.isEdit = true;
      let map = vm.$refs.map.$$getInstance();
      //构造折线编辑对象，并开启折线的编辑状态
      let polygonEditor = new AMap.PolyEditor(map, polygon);
      vm.polygonEditor = polygonEditor;
      polygonEditor.open();
      //关闭多边形编辑polygonEditor.close()触发该方法；
      polygonEditor.on("end", function(event) {});
    },

    // 编辑多边形区域
    edit(idx) {
      if (this.falg == false) {
        this.$message.error("您的商圈尚未编辑完成");
        return;
      }
      this.falg = false;
      var that = this;

      if (this.isDraw) {
        this.endDraw();
      }
      if (this.polygonEditor) {
        this.end();
      }
      this.isEdit = true;
      let pStr = "polygon_" + idx.$index;
      let vm = this;
      let map = vm.$refs.map.$$getInstance();

      let polygon = vm.$refs["polygon_" + idx.$index][0].$$getInstance();

      // 缩放地图到合适的视野级别
      // map.setFitView([polygon]);
      //构造折线编辑对象，并开启折线的编辑状态
      let polygonEditor = new AMap.PolyEditor(map, polygon);
      vm.polygonEditor = polygonEditor;
      polygonEditor.open();
      //关闭多边形编辑polygonEditor.close()触发该方法；
      polygonEditor.on("end", function(event) {
        // event.target 即为编辑后的多边形对象,event.target.getPath()得到编辑完成后的点数组
        let pointArr = event.target.getPath();
        vm.polygons[idx.$index].path = pointArr;
        //console.log(pointArr);
        var obj = {
          path: [],
          businessAreaCode: idx.row.businessAreaCode,
          name: idx.row.name,
          events: {
            click(e) {
              _this.clickEdit(_this, this);
            }
          }
        };
        for (var i = 0; i < pointArr.length; i++) {
          const item = pointArr[i];
          //console.log([item.lng, item.lat]);
          obj.path.push([item.lng, item.lat]);
        }
        that.polygonsTwo.push(obj);
        //console.log(that.polygonsTwo);
      });
    },
    // 结束编辑
    end() {
      this.polygonEditor.close();
      this.isEdit = false;
    },
    // 结束绘制
    endDraw() {
      this.isDraw = false;
    },
    // 确定 传数据给父组件
    sure() {
      if (this.isDraw) {
        this.endDraw();
      }
      if (this.isEdit) {
        this.end();
      }

      for (let i = 0; i < this.polygonsTwo.length; i++) {
        var arr = [];
        const element = this.polygonsTwo[i];
        element.aroundLocations = element.path;
        for (let j = 0; j < element.path.length; j++) {
          const item = element.path[j];
          if (item instanceof Array) {
            arr.push(item);
          } else {
            arr.unshift([item.lng, item.lat]);
          }
        }
        //console.log(arr);
        this.area = Math.round(AMap.GeometryUtil.ringArea(arr));
        //console.log(this.area);
      }
      let center = this.center;
      let polygons = this.polygons;
      let area = this.area;
      let polygonsTwo = this.polygonsTwo;
      let cityCode = this.cityCode;
      let cityName = this.cityName;

      this.$emit("update", polygonsTwo, center, area, cityCode, cityName);
      this.polygonsTwo = [];
      this.falg = true;
    }
  }
};
</script>
<style scoped lang="scss">
.search-box {
  position: absolute;
  top: 0;
  left: 0;
}
.amap-wrapper {
  width: 100%;
  height: 450px;
  position: relative;
}
</style>
